<template>
  <view class="container">
    <!-- 初始状态 -->
    <view class="initial-section" v-if="showInitial">
      <view class="title">抛硬币决定</view>
      <view class="coin-placeholder">
        <image
          @click="flipCoin"
          class="coin-preview"
          mode="aspectFit"
          :src="coinFrontUrl"
        ></image>
        <view @click="flipCoin" class="flip-btn">点击抛硬币</view>
        <view class="slogan-container">
          <view class="slogan">{{ currentSlogan }}</view>
        </view>
      </view>
    </view>

    <!-- 抛硬币动画 -->
    <view class="flipping-section" v-if="showFlipping">
      <view class="coin-container" :class="getAnimationClass">
        <image
          class="coin coin-front"
          mode="aspectFit"
          :src="coinFrontUrl"
        ></image>
        <image
          class="coin coin-back"
          mode="aspectFit"
          :src="coinBackUrl"
        ></image>
      </view>
    </view>

    <!-- 结果展示 -->
    <view class="result-section" v-if="showResult">
      <view class="result-content">
        <image
          class="result-image"
          mode="aspectFit"
          :src="resultImageUrl"
        ></image>
        <view class="result-text">{{ resultText }}</view>
        <view class="result-actions">
          <button class="share-btn" @click="shareResult">保存分享</button>
          <button class="reset-btn" @click="reset">再来一次</button>
        </view>
      </view>
    </view>

    <!-- 隐藏的Canvas，用于生成分享图片 -->
    <canvas
      class="hidden-canvas"
      canvas-id="resultCanvas"
      :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }"
    ></canvas>
    <!-- 统计信息 -->
    <view class="statistics-section">
      <view class="statistics-content">
        <view class="statistics-item">
          <text class="statistics-label">总次数</text>
          <text class="statistics-value">{{ totalFlips }}</text>
        </view>
        <view class="statistics-item">
          <text class="statistics-label">正面</text>
          <text class="statistics-value">{{ frontCount }}</text>
        </view>
        <view class="statistics-item">
          <text class="statistics-label">反面</text>
          <text class="statistics-value">{{ backCount }}</text>
        </view>
        <image
          class="reset-stat-btn"
          src="/static/refresh.png"
          mode="aspectFit"
          @click="resetStatistics"
          @tap="resetStatistics"
          :data-tip="'重置统计'"
        ></image>
      </view>
    </view>
  </view>
</template>
<script>
export default {
  data() {
    return {
      // 页面状态
      showInitial: true,
      showFlipping: false,
      showResult: false,
      isFlipping: false,
      animationType: "", // 'front' 或 'back'，用于控制动画类型

      // 硬币图片URL - 使用绝对路径确保微信小程序Canvas兼容性
      coinFrontUrl: '/static/yingbi-zheng.png',
      coinBackUrl: '/static/yingbi-fan.png',        
      resultFrontUrl: '/static/yingbi-zheng-2.png',        
      resultBackUrl: '/static/yingbi-fan-2.png', 
      // 结果数据
      result: "", // 'front' 或 'back'
      resultText: "",
      resultImageUrl: "",

      // Slogan列表
      slogans: [
        "心流，即决策",
        "对齐一下，宇宙OKR",
        "信噪比越高，决策越玄妙",
        "每一次选择，都是一次成功的量子坍缩",
        "别纠结，你正在创造观察者效应",
        "别给选择上锁，钥匙在你手里",
        "在所有的谨慎之外，有所有可能的未来",
        "温柔地推翻这个世界",
        "成年人的世界，除了容易长胖，其他都不容易——包括做决定",
        "心之所向，素履以往",
        "要么选择，要么被选择",
      ],
      currentSlogan: "",

      // Canvas尺寸
      canvasWidth: 362,
      canvasHeight: 525,

      // 生成的图片路径
      generatedImageUrl: "",

      // 统计数据
      totalFlips: 0,
      frontCount: 0,
      backCount: 0,
    };
  },
  computed: {
    // 计算属性：根据结果返回对应的动画类
    getAnimationClass() {
      return {
        "flipping-front": this.animationType === "front" && this.isFlipping,
        "flipping-back": this.animationType === "back" && this.isFlipping,
      };
    },
  },

  onShareAppMessage() {
    return {
      title: "抛硬币决定器：让概率帮你做选择",
      path: "/pages/coin-flip/coin-flip",
      imageUrl: this.generatedImageUrl || "",
    };
  },
  onShareTimeline() {
    return {
      title: "抛硬币决定器：让概率帮你做选择",
      path: "/pages/coin-flip/coin-flip",
      imageUrl: this.generatedImageUrl || "",
    };
  },
  onLoad() {
    // 设置顶部导航栏
    uni.setNavigationBarColor({
      frontColor: "#ffffff",
      backgroundColor: "#000000",
    });

    // 初始化显示一个随机slogan
    this.updateSlogan();
  },
  methods: {
    // 更新随机slogan
    updateSlogan() {
      const randomIndex = Math.floor(Math.random() * this.slogans.length);
      this.currentSlogan = this.slogans[randomIndex];
    },

    // 抛硬币
    flipCoin() {
      // 隐藏初始界面，显示翻转动画
      this.showInitial = false;
      this.showFlipping = true;

      // 重置动画类型
      this.animationType = "";

      // 随机决定结果
      this.result = Math.random() > 0.5 ? "front" : "back";
      this.resultText = this.result === "front" ? "正面" : "反面";
      this.resultImageUrl =
        this.result === "front" ? this.resultFrontUrl : this.resultBackUrl;

      // 延迟设置动画类型，确保重新渲染
      setTimeout(() => {
        this.animationType = this.result;
        this.isFlipping = true;
      }, 50);

      // 设置翻转动画持续时间（1.2秒）
      const flipDuration = 1300;

      // 动画结束后显示结果
      setTimeout(() => {
        this.isFlipping = false;
        this.showFlipping = false;
        this.showResult = true;
        // 更新统计数据
        this.totalFlips++;
        if (this.result === "front") {
          this.frontCount++;
        } else {
          this.backCount++;
        }
        // 生成分享图片
        this.drawResultAndGenerateImage();
      }, flipDuration);
    },
    // 绘制结果并生成图片
    drawResultAndGenerateImage() {
      const ctx = uni.createCanvasContext("resultCanvas", this);

      // 清空画布
      ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);

      // 设置背景
      ctx.setFillStyle("#1a1a1a");
      ctx.fillRect(0, 0, this.canvasWidth, this.canvasHeight);

      // 直接使用本地路径绘制图片
      const localImagePath = this.resultImageUrl;
      
      // 计算图片位置，使其居中
      const imgWidth = 200;
      const imgHeight = 200;
      const imgX = (this.canvasWidth - imgWidth) / 2;
      const imgY = 80;
      
      // 直接使用本地路径绘制图片
      console.log('直接使用本地路径绘制图片:', localImagePath);
      ctx.drawImage(localImagePath, imgX, imgY, imgWidth, imgHeight);
      
      // 设置文字样式
      ctx.setFillStyle("#ffffff");
      ctx.setTextAlign("center");
      ctx.setTextBaseline("middle");

      // 绘制结果文字
      ctx.setFontSize(24);
      ctx.fillText(`结果: ${this.resultText}`, this.canvasWidth / 2, 320);

      // 绘制slogan
      ctx.setFontSize(16);
      ctx.setFillStyle("#cccccc");
      ctx.fillText(this.currentSlogan, this.canvasWidth / 2, 360);

      // 绘制底部文字
      ctx.setFontSize(14);
      ctx.setFillStyle("#999999");
      ctx.fillText("抛硬币决定器", this.canvasWidth / 2, 420);

      // 提交绘制
      ctx.draw(false, () => {
        // 转换为图片
        this.canvasToImage();
      });
    },

    // 将canvas转换为图片
    canvasToImage() {
      uni.canvasToTempFilePath(
        {
          canvasId: "resultCanvas",
          width: this.canvasWidth,
          height: this.canvasHeight,
          quality: 1,
          success: (res) => {
            this.generatedImageUrl = res.tempFilePath;
          },
          fail: (err) => {
            console.error("生成图片失败:", err);
          },
        },
        this
      );
    },

    // 分享结果
    shareResult() {
      // 延迟执行，确保canvas绘制完成
      setTimeout(() => {
        uni.canvasToTempFilePath(
          {
            canvasId: "resultCanvas",
            width: this.canvasWidth,
            height: this.canvasHeight,
            quality: 1,
            success: (res) => {
              // 优先使用微信原生的分享图片菜单
              if (typeof wx !== "undefined" && wx.showShareImageMenu) {
                wx.showShareImageMenu({
                  path: res.tempFilePath,
                  success: () => {
                    uni.showToast({
                      title: "分享成功",
                      icon: "success",
                    });
                  },
                  fail: (err) => {
                    console.error("显示分享菜单失败:", err);
                    // 分享失败时尝试保存图片
                    if (err.errMsg.indexOf("cancel") < 0) {
                      this.saveImageAsFallback(res.tempFilePath);
                    }
                  },
                });
              } else {
                // 不支持分享菜单时，直接保存图片
                this.saveImageAsFallback(res.tempFilePath);
              }
            },
            fail: (err) => {
              console.error("生成图片失败:", err);
              uni.showToast({
                title: "生成图片失败，请重试",
                icon: "none",
              });
            },
          },
          this
        );
      }, 300);
    },

    // 保存图片作为备选方案
    saveImageAsFallback(tempFilePath) {
      // 检查保存图片授权
      uni.getSetting({
        success: (res) => {
          if (!res.authSetting["scope.writePhotosAlbum"]) {
            // 请求授权
            uni.authorize({
              scope: "scope.writePhotosAlbum",
              success: () => {
                this.doSaveImage(tempFilePath);
              },
              fail: () => {
                uni.showToast({
                  title: "请授权保存图片",
                  icon: "none",
                });
                // 引导用户手动授权
                setTimeout(() => {
                  this.handleAuthDeny();
                }, 1000);
              },
            });
          } else {
            // 已授权，直接保存
            this.doSaveImage(tempFilePath);
          }
        },
      });
    },

    // 执行保存图片操作
    doSaveImage(filePath) {
      uni.saveImageToPhotosAlbum({
        filePath: filePath,
        success: () => {
          uni.showToast({
            title: "图片已保存到相册",
            icon: "success",
            duration: 2000,
          });
        },
        fail: (err) => {
          console.error("保存图片失败:", err);
          uni.showToast({
            title: "保存失败，请重试",
            icon: "none",
          });
        },
      });
    },

    // 处理授权拒绝
    handleAuthDeny() {
      uni.showModal({
        title: "提示",
        content: "需要您授权保存图片到相册",
        success: (res) => {
          if (res.confirm) {
            if (typeof wx !== "undefined" && wx.openSetting) {
              wx.openSetting({
                success: (settingRes) => {
                  console.log("设置结果:", settingRes);
                },
              });
            }
          }
        },
      });
    },

    // 重置
    reset() {
      this.showResult = false;
      this.showFlipping = false;
      this.showInitial = true;
      this.result = "";
      this.resultText = "";
      this.resultImageUrl = "";
      this.generatedImageUrl = "";

      // 更新slogan
      this.updateSlogan();
    },

    // 重置统计数据
    resetStatistics() {
      this.totalFlips = 0;
      this.frontCount = 0;
      this.backCount = 0;
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100vh;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  background-color: #000;
  perspective: 1000px;
}

/* 初始状态样式 */
.initial-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 40rpx;
}

.title {
  font-size: 48rpx;
  color: #ffffff;
  margin-bottom: 32rpx;
  font-weight: bold;
}

.slogan-container {
  padding: 16rpx 40rpx;
  margin-top: 60rpx;
  border-radius: 20rpx;
  background: linear-gradient(
    135deg,
    rgba(255, 255, 255, 0.1) 0%,
    rgba(255, 255, 255, 0.05) 100%
  );
  border: 1rpx solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(10rpx);
}

.slogan {
  font-size: 36rpx;
  color: #ffffff;
  font-style: italic;
  text-align: center;
  line-height: 52rpx;
  font-weight: 500;
  background: linear-gradient(135deg, #ffffff, #e0e0e0);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  animation: sloganGlow 4s ease-in-out infinite alternate;
}

@keyframes sloganGlow {
  0% {
    text-shadow: 0 0 10rpx rgba(255, 255, 255, 0.3);
  }
  100% {
    text-shadow: 0 0 20rpx rgba(255, 255, 255, 0.6),
      0 0 30rpx rgba(255, 255, 255, 0.3);
  }
}

.coin-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.coin-preview {
  width: 300rpx;
  height: 300rpx;
  border-radius: 50%;
  box-shadow: 0 0 40rpx rgba(255, 255, 255, 0.3);
  animation: float 3s ease-in-out infinite;
}

@keyframes float {
  0% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-20rpx);
  }
  100% {
    transform: translateY(0);
  }
}

.flip-btn {
  margin-top: 40rpx;
  font-size: 32rpx;
  color: #ffffff;
  padding: 20rpx 60rpx;
  border-radius: 80rpx;
  background: rgba(255, 255, 255, 0.1);
  border: 1rpx solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 0 20rpx rgba(255, 255, 255, 0.2);
  transition: all 0.3s ease;
}

.flip-btn:active {
  transform: scale(0.95);
  background: rgba(255, 255, 255, 0.2);
}

/* 翻转动画样式 */
.flipping-section {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}

.coin-container {
  width: 300rpx;
  height: 300rpx;
  position: relative;
  transform-style: preserve-3d;
}

.coin {
  position: absolute;
  width: 100%;
  height: 100%;
  backface-visibility: hidden;
  border-radius: 50%;
}

.coin-back {
  transform: rotateY(180deg);
}

/* 正面结果的翻转动画 - 偶数圈，最终显示正面 */
@keyframes flip-front {
  0% {
    transform: translateY(0) translateZ(0) rotateX(0deg);
  }

  40% {
    transform: translateY(-500rpx) translateZ(-100rpx) rotateX(6000deg);
  }

  100% {
    transform: translateY(0) translateZ(0) rotateX(60deg);
  }
}

/* 反面结果的翻转动画 - 奇数圈+半圈，最终显示反面 */
@keyframes flip-back {
  0% {
    transform: translateY(0) translateZ(0) rotateX(0deg);
  }

  40% {
    transform: translateY(-500rpx) translateZ(-100rpx) rotateX(6000deg);
  }
  100% {
    transform: translateY(0) translateZ(0) rotateX(240deg);
  }
}

/* 根据结果应用不同的动画 */
.flipping-front {
  animation: flip-front 1.2s ease-in-out forwards;
}

.flipping-back {
  animation: flip-back 1.2s ease-in-out forwards;
}

/* 结果样式 */
.result-section {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx;
}

.result-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.result-image {
  width: 400rpx;
  height: 400rpx;
  border-radius: 20rpx;
  box-shadow: 0 0 60rpx rgba(255, 255, 255, 0.3);
  animation: resultAppear 0.8s ease-out;
}

@keyframes resultAppear {
  0% {
    opacity: 0;
    transform: scale(0.8) translateY(50rpx);
  }
  100% {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
}

.result-text {
  margin-top: 40rpx;
  font-size: 48rpx;
  color: #ffffff;
  font-weight: bold;
  animation: textAppear 0.8s ease-out 0.3s both;
}

@keyframes textAppear {
  0% {
    opacity: 0;
    transform: translateY(20rpx);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

.result-actions {
  display: flex;
  gap: 30rpx;
  margin-top: 60rpx;
  width: 100%;
  animation: buttonsAppear 0.8s ease-out 0.6s both;
}

@keyframes buttonsAppear {
  0% {
    opacity: 0;
    transform: translateY(30rpx);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

.share-btn {
  flex: 1;
  background-color: rgba(255, 255, 255, 0.1);
  color: #ffffff;
  font-size: 32rpx;
  border-radius: 80rpx;
  height: 96rpx;
  line-height: 96rpx;
  border: 1rpx solid rgba(255, 255, 255, 0.3);
}

.reset-btn {
  flex: 1;
  background-color: rgba(255, 255, 255, 0.1);
  color: #ffffff;
  font-size: 32rpx;
  border-radius: 80rpx;
  height: 96rpx;
  line-height: 96rpx;
  border: 1rpx solid rgba(255, 255, 255, 0.3);
}

.hidden-canvas {
  position: absolute;
  left: -9999px;
  top: -9999px;
  opacity: 0;
}

/* 统计信息样式 */
.statistics-section {
  padding: 30rpx 40rpx;
  padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
  background: rgba(255, 255, 255, 0.05);
  border-top: 1rpx solid rgba(255, 255, 255, 0.1);
}

.statistics-content {
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.statistics-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.statistics-label {
  font-size: 24rpx;
  color: #cccccc;
  margin-bottom: 10rpx;
}

.statistics-value {
  font-size: 36rpx;
  color: #ffffff;
  font-weight: bold;
}

.reset-stat-btn {
  width: 60rpx;
  height: 60rpx;
  opacity: 0.7;
  transition: opacity 0.3s ease;
}

.reset-stat-btn:active {
  opacity: 1;
  transform: rotate(360deg);
  transition: all 0.5s ease;
}
</style>
